package com.cjzuji.rental.listeners;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.cjzuji.rental.Bean.OrderData;
import com.cjzuji.rental.service.OrderService;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class OrderDataListener implements ReadListener<Map<Integer, String>> {

    private static final int BATCH_COUNT = 100;
    private List<OrderData> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private OrderData currentOrder;
    private int currentRowIndex = 0;
    private final OrderService orderService;

    // 用于匹配键值对的正则表达式
    private static final Pattern KEY_VALUE_PATTERN = Pattern.compile("^([^:\n]+):?(.*)$");

    public OrderDataListener(OrderService orderService) {
        System.out.println("第一步，打印获取数据");
        System.out.println(orderService);
        this.orderService = orderService;
    }

    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext context) {
        // 只处理第一列数据（索引0）
        String cellContent = data.get(0);
        if (cellContent == null || cellContent.trim().isEmpty()) {
            log.info("直接执行 +++++");
            currentRowIndex++;
            return;
        }

        log.debug("处理第{}行数据: {}", currentRowIndex + 1, cellContent);

        // 每三行一组数据（A,B,C）
        int groupIndex = currentRowIndex % 3;

        // A行开始，创建新订单
        if (groupIndex == 0) {
            currentOrder = new OrderData();
            processBasicInfo(cellContent);
        }
        // B行处理商品信息
        else if (groupIndex == 1) {
            processProductInfo(cellContent);
        }
        // C行处理用户信息
        else if (groupIndex == 2) {
            processUserInfo(cellContent);
            // 完整的一组数据，添加到缓存
            cachedDataList.add(currentOrder);

            // 批量处理
            if (cachedDataList.size() >= BATCH_COUNT) {
                saveData();
                cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
            }
        }

        currentRowIndex++;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        log.info("所有数据解析完成！共处理{}行数据", currentRowIndex);
    }

    /**
     * 处理A行数据（订单基本信息）
     */
    private void processBasicInfo(String content) {
        System.out.println("打印获取数据值" + content);
        String[] lines = content.split("\n");
        String currentKey = null;

        for (String line : lines) {
            line = line.trim();
            if (line.isEmpty()) continue;

            Matcher matcher = KEY_VALUE_PATTERN.matcher(line);
            if (matcher.matches()) {
                String key = matcher.group(1).trim();
                String value = matcher.group(2).trim();
                // 如果匹配到键（以冒号结尾或包含冒号）
                if (line.contains(":") || line.endsWith(":")) {
                    currentKey = key;
                    if (!value.isEmpty()) {
                        currentOrder.getBasicInfo().put(currentKey, value);
                        currentKey = null;
                    }
                }
                // 如果是值且前面有键
                else if (currentKey != null) {
                    currentOrder.getBasicInfo().put(currentKey, line);
                    currentKey = null;
                }
                // 独立行（如"首租订单"）
                else {
                    currentOrder.getBasicInfo().put(key, "");
                }
            }
        }
    }

    /**
     * 处理B行数据（商品信息）
     */
    private void processProductInfo(String content) {
        // 特殊处理B行数据
        String[] parts = content.split("\n");

        // 第一行作为订单类型
        if (parts.length > 0) {
            currentOrder.getProductInfo().put("订单类型", parts[0].trim());
        }

        // 第二行作为店铺信息
        if (parts.length > 1) {
            currentOrder.getProductInfo().put("店铺名称", parts[1].trim());
        }

        // 处理ID
        for (String line : parts) {
            if (line.startsWith("ID：")) {
                currentOrder.getProductInfo().put("商品ID", line.substring(3).trim());
            }
        }

        // 处理商品描述（包含中括号的内容）
        for (String line : parts) {
            if (line.startsWith("【") && line.endsWith("】")) {
                currentOrder.getProductInfo().put("商品描述", line.substring(1, line.length() - 1));
            }
        }

        // 处理规格（如"黑色钛金属 256G"）
        for (String line : parts) {
            if (line.matches(".+\\s+\\d+[GgTt]")) {
                currentOrder.getProductInfo().put("商品规格", line.trim());
            }
        }

        // 处理支付方式
        for (String line : parts) {
            if (line.contains("支付宝") || line.contains("微信")) {
                currentOrder.getProductInfo().put("支付方式", line.trim());
            }
        }

        // 处理优惠信息
        for (String line : parts) {
            if (line.startsWith("优惠券：")) {
                currentOrder.getProductInfo().put("优惠信息", line.substring(4).trim());
            }
        }
    }

    /**
     * 处理C行数据（用户信息）
     */
    private void processUserInfo(String content) {
        String[] lines = content.split("\n");
        String currentKey = null;

        for (String line : lines) {
            line = line.trim();
            if (line.isEmpty()) continue;

            // 处理用户姓名
            if (currentOrder.getUserInfo().get("用户姓名") == null &&
                    line.matches("^[\u4e00-\u9fa5]+$")) {
                currentOrder.getUserInfo().put("用户姓名", line);
                continue;
            }

            // 处理电话号码
            if (currentOrder.getUserInfo().get("联系电话") == null &&
                    line.matches("1[3-9]\\d{9}")) {
                currentOrder.getUserInfo().put("联系电话", line);
                continue;
            }

            // 处理地址（包含"省"、"市"等字眼）
            if (currentOrder.getUserInfo().get("收货地址") == null &&
                    (line.contains("省") || line.contains("市") || line.contains("区") || line.contains("县"))) {
                currentOrder.getUserInfo().put("收货地址", line);
                continue;
            }

            // 处理身份证（18位数字或17位数字+X）
            if (currentOrder.getUserInfo().get("身份证号") == null &&
                    line.matches("\\d{17}[\\dXx]")) {
                currentOrder.getUserInfo().put("身份证号", line);
                continue;
            }

            // 处理"下单用户"标签
            if (line.equals("下单用户")) {
                currentKey = "下单用户";
                continue;
            }

            // 如果没有匹配任何规则，添加到备注
            currentOrder.getUserInfo().put("备注",
                    currentOrder.getUserInfo().getOrDefault("备注", "") + line + ";");
        }
    }

    private void saveData() {
        if (cachedDataList.isEmpty()) return;

        log.info("开始处理{}条订单数据...", cachedDataList.size());
        orderService.processOrders(cachedDataList);
        log.info("订单数据处理完成！");
    }
}